package org.sjcx.jsoup;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


/**
 * @author user
 * 获取连接状态
 */
public class HttpResponse {

    public static void main(String[] args) throws MalformedURLException {
        String link = "https://www.baidu.com/";
        URL url = new URL(link);
        System.out.println(getHttpResponseCode(url));

    }

    public static int getHttpResponseCode(URL url) {
        HttpURLConnection httpurlconnection = null;
        int responsecode = -1;
        try {
            URLConnection urlconnection = url.openConnection();
            urlconnection.connect();
            if (!(urlconnection instanceof HttpURLConnection)) {
                // urlconnection.disconnect();
                return responsecode;
            }

            httpurlconnection = (HttpURLConnection) urlconnection;
            // httpurlconnection.setFollowRedirects(true);

            // 获取返回码,通过responsecode 就可以知道网页的状态,我们也是通过此字段用于判断请求的资源是否存在
            responsecode= httpurlconnection.getResponseCode();
            switch (responsecode) {
                // here valid codes!
                case HttpURLConnection.HTTP_OK:
                case HttpURLConnection.HTTP_MOVED_PERM:
                case HttpURLConnection.HTTP_MOVED_TEMP:
                    break;
                default:
                    httpurlconnection.disconnect();
            }
        } catch (Exception ioexception) {
            if (httpurlconnection != null) {
                httpurlconnection.disconnect();
            }
            return responsecode;
        }
        return responsecode;
    }
}